var gulp = require('gulp');
var sass = require('gulp-sass');
var connect = require('gulp-connect');
var sourcemaps = require('gulp-sourcemaps')
var autoprefixer = require('gulp-autoprefixer')
var cleanCss = require("gulp-clean-css")
var ejs = require('gulp-ejs')
var clean = require('gulp-clean')
var gulpSequence = require('gulp-sequence')

gulp.task('sass', function() {
    return gulp.src('./static/css/sass/*.scss')
        .pipe(sourcemaps.init())
        .pipe(autoprefixer({
            browsers: ['last 50 versions', 'last 50 Explorer versions', 'Android >= 4.0'],
        }))
        .pipe(sass({ outputStyle: 'compressed' }))
        .pipe(cleanCss())
        .pipe(sourcemaps.write({ includeContent: false }))
        .pipe(gulp.dest('./static/css'))
        .pipe(connect.reload())
})


gulp.task('webserver', function() {
    return connect.server({
        livereload: true,
        // host: '192.168.11.89',
    });
});


gulp.task('ejs', function() {
    setTimeout(() => {
        gulp.src('./views/*.html')
            .pipe(ejs().on('error', function(err) {　　　　
                console.log(err)　　　
                this.emit('end');　　
            }))　　
            .pipe(gulp.dest('./dist/views'))
            .pipe(connect.reload());
    }, 100)

});


gulp.task('watch', function() {
    gulp.watch('./static/css/**/*.scss', ['sass']);
    gulp.watch('./views/**/*.html', ['ejs']);
})

gulp.task('copy-js', function() {
    return gulp.src('./static/**/*.js')
        .pipe(gulp.dest('./dist/static'))
});

gulp.task('copy-css', function() {
    return gulp.src('./static/**/*.css')
        .pipe(gulp.dest('./dist/static'))
});

gulp.task('copy-images', function() {
    return gulp.src('./static/**/*.png')
        .pipe(gulp.dest('./dist/static'))
});


gulp.task("clean", function() {
    return gulp.src('./dist')
        .pipe(clean());
})

gulp.task('dev', gulpSequence('clean', 'sass', 'ejs', 'webserver', 'watch'));

gulp.task('build', gulpSequence('clean', 'sass', 'ejs', 'copy-js', 'copy-images', 'copy-css'));